package com.taoye.thread;

/**
 * 使用notify唤醒一个线程或者使用notifyAll唤醒多个线程
 *
 * @author : Mr.Tao
 * @version : 1.0
 * @date : 2022/4/4 10:31
 **/
public class Demo40 {
    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        Thread t = new Demo40ThreadA(lock);
        t.setName("A");
        t.start();
        Thread t2 = new Demo40ThreadA(lock);
        t2.setName("B");
        t2.start();
        Thread t3 = new Demo40ThreadA(lock);
        t3.setName("C");
        t3.start();
        Thread.sleep(2000);
        Thread t4 = new Demo40ThreadB(lock);
        t4.setName("唤醒线程");
        t4.start();
    }
}

class Demo40ThreadA extends Thread {
    private Object lock;

    public Demo40ThreadA(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            try {
                System.out.println("我是线程" + Thread.currentThread().getName() + "，现在开始进入等待状态了");
                lock.wait();
                System.out.println("我是线程" + Thread.currentThread().getName() + "，现在等待结束了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Demo40ThreadB extends Thread {
    private Object lock;

    public Demo40ThreadB(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            //调用一次notify()方法可随机唤醒一个等待中的线程
            //lock.notify();
            //唤醒全部线程要使用notifyAll()方法
            lock.notifyAll();
        }
    }
}